local Replaces = {"dreadstonehat", "eyemaskhat"}
local e_util = require "libs/entutil"
local ahe
local p_util = require "libs/playerutil"

local function unequip(player, meta)
    local yes = meta.item.prefab and table.contains(Replaces, meta.item.prefab)
    if yes and ahe then
        ahe.AnimState:PlayAnimation("activate_pst")
        ahe:Remove()
        ahe = nil
    end
    local head = p_util:GetEquip("head")
    if head and table.contains(Replaces, head.prefab) then
        local anim = player.AnimState
        if anim then
            anim:ClearOverrideSymbol("swap_hat")
            anim:ClearOverrideSymbol("headbase_hat")
            anim:Show("HAIR")
            anim:Show("HEAD")
            anim:Show("HAIR_NOHAT")
        end
    end
end

local function equip(player, meta)
    local yes = meta.item.prefab and table.contains(Replaces, meta.item.prefab)
    local head = p_util:GetEquip("head")
    yes = yes or (head and table.contains(Replaces, head.prefab))
    
    if yes then
        if not ahe then
            ahe = GLOBAL.SpawnPrefab("alterguardian_hat_equipped")
            ahe.entity:SetParent(player.entity)
            ahe.entity:AddFollower()
            ahe.Follower:FollowSymbol(player.GUID, "hair", 0, 0, 0) -- "swap_hat"
            ahe.AnimState:PlayAnimation("activate_pre")
            ahe.AnimState:PushAnimation("activate_loop", true)
        end
        local anim = player.AnimState
        if anim then
            anim:ClearOverrideSymbol("swap_hat")
            anim:ClearOverrideSymbol("headbase_hat")
            anim:Show("HAIR")
            anim:Show("HEAD")
            anim:Show("HAIR_NOHAT")
        end
    end
end

AddPlayerActivatedFunc(function(player)
    player:ListenForEvent("unequip_withhx", unequip)
    player:ListenForEvent("equip_withhx", equip)
end)

AddPrefabPostInit("sewing_mannequin", function(inst)
    inst:DoTaskInTime(0.5, function(inst)
        local color = inst and inst.components and inst.components.talker and inst.components.talker.colour
        if color then
            color.x = 0
            color.y = 1
            color.z = 0
        end
    end)
end)